package com.dragon.www.haier.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dragon.www.haier.R;
import com.dragon.www.haier.entity.Device;
import com.dragon.www.haier.entity.DeviceListInfo;
import com.dragon.www.haier.entity.Room;
import com.dragon.www.haier.entity.RoomListInfo;
import com.dragon.www.haier.entity.ServiceResult;
import com.dragon.www.haier.entity.User;
import com.dragon.www.haier.fragment.FirstScreenFragment;
import com.dragon.www.haier.fragment.SecondScreenFragment;
import com.dragon.www.haier.net.NetHelper;
import com.dragon.www.haier.net.NetUtils;
import com.dragon.www.haier.popupwindow.RoomPopWindow;
import com.dragon.www.haier.popupwindow.Setpopwindow;
import com.dragon.www.haier.util.Config;
import com.dragon.www.haier.util.Utils;
import com.dragon.www.haier.view.NoScrollViewPager;
import com.dragon.www.haier.view.dialog.LoginDialog;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity implements View.OnClickListener{

    public static final String TYPE_LAMP = "1";         //灯光
    public static final String TYPE_AIR = "9";          //空调
    public static final String TYPE_CURTAIN = "10";      //窗帘
    public static final String TYPE_ENTANCEGUARD = "8";  //门禁
    public static final String TYPE_HUMIDIFIER = "6";   //加湿器
    public static final String TYPE_PLANTWALL = "7";   //植物墙
    /**
     * HEZI
     */
    public static final String TYPE_CONTROLLER = "7";

    public final int ACTIVITY_RESULT_LOGIN = 10;

    private TextView textViewTitle;
    private ImageView imageView_setting;
    private CheckBox cb_all_lamp;
    private ImageView imageView_login_out;
    private ImageView iv_video;
//    private ImageView imageView_login_out1;
    private Setpopwindow settingPopWindow;
    private LoginDialog mLoginDialog;

    private int width;
    private int height;
    public NoScrollViewPager mViewPager;
    private MainViewPagerAdapter mMainViewPagerAdapter;
    public List<Fragment> fragments;
    private FirstScreenFragment mFirstScreenFragment;
    private SecondScreenFragment mSecondScreenFragment;
    private List<Room> mRooms = null;
    private List<Device> mDevices = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }

    @Override
    protected void onResume(){
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void initView() {
        setContentView(R.layout.activity_main);
        textViewTitle = (TextView) findViewById(R.id.textView_title);
        imageView_setting = (ImageView) findViewById(R.id.iv_setting);
        cb_all_lamp = (CheckBox) findViewById(R.id.all_lamp_cb);
        imageView_login_out = (ImageView) findViewById(R.id.iv_login_out);
//        imageView_login_out1 = (ImageView) findViewById(R.id.iv_login_out1);
        iv_video = (ImageView) findViewById(R.id.iv_video);
        iv_video.setOnClickListener(this);

        imageView_setting.setOnClickListener(this);
        imageView_login_out.setOnClickListener(this);
//        imageView_login_out1.setOnClickListener(this);
        cb_all_lamp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked == true){
                    turnAllLampOn();
                }else{
                    turnAllLampOff();
                }
            }
        });

        fragments = new ArrayList<>();
        mFirstScreenFragment = new FirstScreenFragment();
        mFirstScreenFragment.setOnOperateListener(new FirstScreenFragment.OnOperateListener() {
            @Override
            public void onHideOperateBar() {
                hideOperateBar();
            }

            @Override
            public void onShowOperateBar() {
                showOperateBar();
            }

            @Override
            public void onSelectRoomChanged(Room changeRoom) {
                mSecondScreenFragment.selectRoom(changeRoom);
                getRoomDeviceFromNetwork(changeRoom);
            }
        });
        fragments.add(mFirstScreenFragment);
        mSecondScreenFragment = new SecondScreenFragment();
        mSecondScreenFragment.setOnOperateListener(new SecondScreenFragment.OnOperateListener() {
            @Override
            public void onHideOperateBar() {
                hideOperateBar();
            }

            @Override
            public void onShowOperateBar() {
                showOperateBar();
            }
        });
        fragments.add(mSecondScreenFragment);

        mMainViewPagerAdapter = new MainViewPagerAdapter(getApplicationContext(), getSupportFragmentManager());
        mViewPager = (NoScrollViewPager) findViewById(R.id.viewpager);
        mViewPager.setAdapter(mMainViewPagerAdapter);

        //如果用户已经登录，自动获取房间智能设备
        if( Utils.isUserLogin() ){
            imageView_login_out.setImageResource(R.drawable.login_out);
            getRoomFromNetwork();
        }else{
            imageView_login_out.setImageResource(R.drawable.login);
        }
    }

    public void initData() {
        WindowManager wm = this.getWindowManager();
        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();
        Config.setScreenSize(this);
    }

    @Override
    public void onClick(View v) {
        if( settingPopWindow != null ){
            //连续快速点击时，操作无效
            return;
        }
        switch (v.getId()) {

            case R.id.iv_login_out:
                //用户未登录弹出登录提示，已登录的话提示注销
                if( !Utils.isUserLogin() ){
                    Intent intent = new Intent(this, com.dragon.www.haier.activity.LoginActivity.class);
                    startActivityForResult(intent, ACTIVITY_RESULT_LOGIN);
                    Toast.makeText(MainActivity.this, "用户尚未登陆，请您先登陆！", Toast.LENGTH_SHORT).show();
                }else{
                    showLoginDialog(Config.getUserInfo());
                }
                break;

            default:
                Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按返回键以退出", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出用户登录状态
     * 2016/06/01
     */
    private void logoutUser(){
        User user = new User();
        Config.setUserInfo(user);
        imageView_login_out.setImageResource(R.drawable.login);
    }

    /**
     * 从网络获取房间及设备
     * 2016/06/01
     */
    public void getRoomFromNetwork() {
        NetHelper.getRooms(this, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getCode().equals("0000")) {
                    //保存房间信息
                    final RoomListInfo roomListInfo = (RoomListInfo) rspData;
                    SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("itcastPreference", Context.MODE_PRIVATE);
                    mRooms = roomListInfo.getRooms();
                    for (Room x:mRooms
                         ) {
                        x.setImgPath(sharedPreferences.getString(String.valueOf(x.getRoomid()), ""));
                    }
                    mFirstScreenFragment.setRooms(mRooms);
                    mSecondScreenFragment.setRooms(mRooms);
                } else {
                    Toast.makeText(MainActivity.this, "获取房间信息失败，原因" + rspData.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        }, RoomListInfo.class);
    }

    /**
     * 从网络获取房间对应的设备
     * 2016/06/01
     */
    public void getRoomDeviceFromNetwork(Room selectRoom){
        if( selectRoom != null ){
            NetHelper.getDevices(MainActivity.this, selectRoom.getRoomid(), new NetUtils.NetCallBack<ServiceResult>() {
                @Override
                public void success(ServiceResult rspData) {
                    if (rspData.getCode().equals("0000")) {
                        final DeviceListInfo deviceListInfo = (DeviceListInfo) rspData;
                        mDevices = deviceListInfo.getDevices();
                        mFirstScreenFragment.setDevices(mDevices);
                        mSecondScreenFragment.setDevices(mDevices);
                    }else{
                        Toast.makeText(MainActivity.this, "获取房间中的设备失败，原因"+rspData.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void failed(String msg) {
                    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            }, DeviceListInfo.class);
        }
    }

    /**
     * 点击了主布局最上面的小灯按钮后关闭所有灯光设备
     * 2016/06/01
     */
    public void turnAllLampOff(){

    }

    /**
     * 点击了主布局最上面的小灯按钮后打开所有灯光设备
     * 2016/06/01
     */
    public void turnAllLampOn(){

    }

    /**
     * 显示主布局上层的操作菜单
     * 2016/06/01
     */
    public void showOperateBar() {
        imageView_login_out.setVisibility(View.VISIBLE);
        mViewPager.setCanScroll(false);
        settingPopWindow = null;
    }

    /**
     * 隐藏主布局上层的操作菜单
     * 2016/06/01
     */
    public void hideOperateBar(){
        imageView_login_out.setVisibility(View.GONE);
        mViewPager.setCanScroll(false);
    }

    public void showLoginDialog(final User user) {
        mLoginDialog = new LoginDialog(this);
        mLoginDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mLoginDialog.setUser(user);
        mLoginDialog.setLisntener(new LoginDialog.OnSelectListener() {
            @Override
            public void loginout() {
                logoutUser();
                mLoginDialog.dismiss();
                Toast.makeText(MainActivity.this, "用户已退出！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void changepassword() {
                mLoginDialog.dismiss();
                Intent intent = new Intent(MainActivity.this, com.dragon.www.haier.activity.PasswordChangeActivity.class);
                startActivity(intent);
            }
        });
        mLoginDialog.show();
    }

    /**
     * 首页viewpager适配器
     * 2016/06/01
     */
    public class MainViewPagerAdapter extends FragmentStatePagerAdapter {
        private List<String> data = new ArrayList<>();
        public MainViewPagerAdapter(Context context, FragmentManager fm) {
            super(fm);
            data.add("首页");
            data.add("会议情景");
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return data.get(position);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
//            return fragments.get(0);
        }

        @Override
        public int getCount() {
            return data.size();
        }
    }

    /**
     * 对相册选择图片后的回掉
     * 2016/06/01
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //相册取得了照片
            case RoomPopWindow.PHOTO_REQUEST_GALLERY:
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = data.getData();
//                    Room room = (Room)data.getSerializableExtra("W");
                    mFirstScreenFragment.roomPopWindow.setFilePath(uri);
                }
                break;
            //登录返回结果
            case ACTIVITY_RESULT_LOGIN:
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(MainActivity.this, "您已成功登陆！", Toast.LENGTH_SHORT).show();
                    imageView_login_out.setImageResource(R.drawable.login_out);
                    getRoomFromNetwork();
                }
                break;
            default:
                break;
        }
    }
}
